import { useState, useCallback, useEffect } from 'react';
import { message } from 'antd';
import { platformUsersApi } from '../../services/platform/api/platformUsersApi';
import { platformRolesApi } from '../../services/platform/api/platformRolesApi';
import { useAsyncState } from '../common/useErrorHandler';
import type { PlatformUser } from '../../types/platform';

// 平台用户表单数据类型（包含密码字段）
export interface PlatformUserFormData {
  id?: string | number;
  username: string;
  password?: string;
  confirmPassword?: string;
  realName: string;
  email: string;
  phone?: string;
  avatar?: string;
  status: 'active' | 'inactive' | 'locked';
  isSuperAdmin?: boolean;
  roleIds?: string;
  platformRoles?: string[];
  accessibleTenants?: string[];
  remark?: string;
}

// 平台用户查询参数
export interface PlatformUserQuery {
  page?: number;
  size?: number;
  search?: string;
  status?: string;
  roleId?: string;
  dateRange?: [string, string];
}

// 分页响应类型
interface PlatformPageResponse<T> {
  records: T[];
  total: number;
  current: number;
  size: number;
}

/**
 * 平台用户管理 hooks
 * 提供用户的增删改查、状态管理、角色管理等功能
 */
export const usePlatformUsers = () => {
  // 状态管理
  const [users, setUsers] = useState<PlatformUser[]>([]);
  const [availableRoles, setAvailableRoles] = useState<any[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');

  const { executeAsync, hasAnyLoading, hasError, error, clearError } = useAsyncState();

  // 加载用户列表
  const loadUsers = useCallback(async () => {
    return executeAsync('loadUsers', async () => {
      const response = await platformUsersApi.getUsers({
        page: pagination.current,
        size: pagination.pageSize,
        search: searchText,
        status: statusFilter === 'all' ? undefined : 
                statusFilter === 'active' ? 1 :
                statusFilter === 'locked' ? 2 : 0
      });

      // 转换用户数据格式
      const transformedUsers = ((response as any).records || []).map((user: any) => {
        // 处理角色字段：优先使用platformRoles数组，如果没有则从roleIds字符串解析
        let platformRoles: string[] = [];
        if (user.platformRoles && Array.isArray(user.platformRoles)) {
          platformRoles = user.platformRoles;
        } else if (user.roleIds && typeof user.roleIds === 'string') {
          platformRoles = user.roleIds.split(',').filter(Boolean);
        } else if (user.roleCodes && Array.isArray(user.roleCodes)) {
          platformRoles = user.roleCodes;
        }
        
        return {
          ...user,
          status: user.status === 1 ? 'active' as const : user.status === 2 ? 'locked' as const : 'inactive' as const,
          platformRoles,
          role: platformRoles[0] || 'user'
        };
      }) as PlatformUser[];
      
      setUsers(transformedUsers);
      setPagination(prev => ({
        ...prev,
        total: (response as any).total || 0,
        current: (response as any).current || prev.current,
      }));

      return transformedUsers;
    });
  }, [executeAsync, pagination.current, pagination.pageSize, searchText, statusFilter]);

  // 加载可用角色列表
  const loadAvailableRoles = useCallback(async () => {
    return executeAsync('loadAvailableRoles', async () => {
      const roles = await platformRolesApi.getAllRoles();
      setAvailableRoles(roles || []);
      return roles;
    });
  }, [executeAsync]);

  // 获取用户详情
  const getUserDetail = useCallback(async (userId: string | number) => {
    return executeAsync('getUserDetail', async () => {
      return await platformUsersApi.getUser(userId);
    });
  }, [executeAsync]);

  // 创建用户
  const createUser = useCallback(async (userData: PlatformUserFormData) => {
    return executeAsync('createUser', async () => {
      // 转换数据格式以匹配API接口
      const userWithPassword = {
        ...userData,
        id: userData.id?.toString(), // 确保id是string类型
        password: userData.password || '123456', // 默认密码
      };
      await platformUsersApi.createUser(userWithPassword);
      message.success('用户创建成功');
      await loadUsers();
    });
  }, [executeAsync, loadUsers]);

  // 更新用户
  const updateUser = useCallback(async (userData: PlatformUserFormData) => {
    return executeAsync('updateUser', async () => {
      if (!userData.id) {
        throw new Error('用户ID不能为空');
      }
      // 转换数据格式以匹配API接口
      const updateData = {
        ...userData,
        id: userData.id.toString(), // 确保id是string类型
      };
      await platformUsersApi.updateUser(userData.id, updateData);
      message.success('用户更新成功');
      await loadUsers();
    });
  }, [executeAsync, loadUsers]);

  // 删除用户
  const deleteUser = useCallback(async (userIds: string[]) => {
    return executeAsync('deleteUser', async () => {
      await platformUsersApi.deleteUser(userIds[0]);
      message.success('用户删除成功');
      await loadUsers();
    });
  }, [executeAsync, loadUsers]);

  // 切换用户状态
  const toggleUserStatus = useCallback(async (userId: string | number, status: 'active' | 'inactive' | 'locked') => {
    return executeAsync('toggleUserStatus', async () => {
      if (status === 'active' || status === 'locked') {
        await platformUsersApi.toggleUserStatus(userId, status);
        message.success(`用户已${status === 'active' ? '启用' : '锁定'}`);
      } else {
        // 对于inactive状态，使用locked状态代替
        await platformUsersApi.toggleUserStatus(userId, 'locked');
        message.success('用户已禁用');
      }
      await loadUsers();
    });
  }, [executeAsync, loadUsers]);

  // 重置用户密码
  const resetUserPassword = useCallback(async (userId: string | number) => {
    return executeAsync('resetUserPassword', async () => {
      const result = await platformUsersApi.resetPassword(userId);
      message.success(`密码重置成功，新密码：${result.newPassword}`);
      return result;
    });
  }, [executeAsync]);

  // 搜索处理
  const handleSearch = useCallback((value: string) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 状态筛选处理
  const handleStatusFilter = useCallback((status: string) => {
    setStatusFilter(status);
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  // 分页处理
  const handlePageChange = useCallback((page: number, pageSize?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  }, []);

  // 重置筛选条件
  const resetFilters = useCallback(() => {
    setSearchText('');
    setStatusFilter('all');
    setPagination({ current: 1, pageSize: 10, total: 0 });
  }, []);

  // 刷新数据
  const refresh = useCallback(() => {
    return loadUsers();
  }, [loadUsers]);

  // 初始化加载
  useEffect(() => {
    loadUsers();
  }, [pagination.current, pagination.pageSize, searchText, statusFilter]);

  useEffect(() => {
    loadAvailableRoles();
  }, []);

  return {
    // 状态
    users,
    availableRoles,
    pagination,
    searchText,
    statusFilter,
    loading: hasAnyLoading,
    error,
    
    // 操作方法
    loadUsers,
    loadAvailableRoles,
    getUserDetail,
    createUser,
    updateUser,
    deleteUser,
    toggleUserStatus,
    resetUserPassword,
    
    // 工具方法
    handleSearch,
    handleStatusFilter,
    handlePageChange,
    resetFilters,
    refresh,
    clearError,
  };
};

export default usePlatformUsers;